package com.dreamder.view;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.dreamder.model.CategoriaBeanTO;
import com.dreamder.model.SonhoBeanTO;
import com.dreamder.model.UsuarioBeanTO;
import com.dreamder.service.SonhoService;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class DetalheSonhoActivity extends Activity {

	private ListView listaParticipantes;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_detalhe_sonho);

		Intent i = getIntent();
		Bundle b = i.getExtras();
		SonhoBeanTO sonho = (SonhoBeanTO) b.get("sonho");
		Boolean meu = (Boolean) b.get("meusSonhos");

		if (meu != null && meu) {
			listaParticipantes = (ListView) findViewById(R.id.participantesSonho);
			TextView label = (TextView) findViewById(R.id.lblParticipantes);
			label.setVisibility(TextView.VISIBLE);
			listaParticipantes.setVisibility(ListView.VISIBLE);

			List<String> usuarios = new ArrayList<String>();
			String nome = "";

			for (UsuarioBeanTO u : sonho.getUsuariosParticipantes()) {
				nome = new String();
				nome = u.getNome();
				usuarios.add(nome);
			}

			ListAdapter listAdapter = new ArrayAdapter<String>(
					DetalheSonhoActivity.this,
					android.R.layout.simple_list_item_1, usuarios);

			listaParticipantes.setAdapter(listAdapter);
		}

		CarregaSonhoTask task = new CarregaSonhoTask();

		task.execute(sonho.getId());
	}

	public void participar(View v) {

		UsuarioBeanTO usuario = new UsuarioBeanTO();

		SharedPreferences pref = getSharedPreferences("DreamderLogin", 0);
		Long id = pref.getLong("idUsuario", 0L);

		usuario.setId(id);

		Intent i = getIntent();
		Bundle b = i.getExtras();
		SonhoBeanTO sonho = (SonhoBeanTO) b.get("sonho");

		sonho.setUsuariosParticipantes(new ArrayList<UsuarioBeanTO>());
		sonho.getUsuariosParticipantes().add(usuario);

		ParticiparSonhoTask task = new ParticiparSonhoTask();

		task.execute(sonho);

	}

	private class CarregaSonhoTask extends AsyncTask<Long, Void, String> {

		private SonhoService service;
		private ProgressDialog progress;

		@Override
		protected void onPreExecute() {

			progress = ProgressDialog.show(DetalheSonhoActivity.this,
					"Aguarde", "Carregando sonho...", true, true);

		}

		@Override
		protected String doInBackground(Long... params) {

			service = new SonhoService();
			return service.carregaSonhoJSON(params[0]);

		}

		@Override
		protected void onPostExecute(String result) {

			if (!"ERRO".equals(result)) {
				try {

					JSONObject json = new JSONObject(result);

					// leitura do sonho
					JSONObject item = json.getJSONObject("sonho");
					SonhoBeanTO sonho = new SonhoBeanTO();
					
					GsonBuilder builder = new GsonBuilder();
					builder.setDateFormat("dd-MM-yyyy");
					Gson gson = builder.create(); 
					
					sonho.setTitulo(item.getString("titulo"));
					sonho.setId(item.getLong("id"));
					sonho.setResumo(item.getString("resumo"));
					sonho.setDsDetalhada(item.getString("dsDetalhada"));
					

					// leitura da categoria
					CategoriaBeanTO cat = new CategoriaBeanTO();
					String catStr = item.getString("categoria");
					cat = gson.fromJson(catStr, CategoriaBeanTO.class);
					sonho.setCategoria(cat);

					// leitura do usuario dono
					UsuarioBeanTO u = new UsuarioBeanTO();
					JSONObject usuario = item.getJSONObject("dono");
					u.setNome(usuario.getString("nome"));
					u.setId(usuario.getLong("id"));
					sonho.setDono(u);

					// atualizacao da tela
					TextView titulo = (TextView) findViewById(R.id.tituloSonhoDet);
					titulo.setText(sonho.getTitulo() + " - " + sonho.getId());

					TextView resumo = (TextView) findViewById(R.id.resumoSonhoDet);
					resumo.setText(sonho.getResumo());

					TextView descricao = (TextView) findViewById(R.id.detalhesSonhoDet);
					descricao.setText(sonho.getDsDetalhada());

					TextView dono = (TextView) findViewById(R.id.donoSonhoDet);
					dono.setText("Sonhador: " + sonho.getDono().getNome());

					TextView categoria = (TextView) findViewById(R.id.catSonhoDet);
					categoria.setText("Categoria: "
							+ sonho.getCategoria().getDescricao());

					progress.dismiss();

				} catch (JSONException e) {
					e.printStackTrace();
					Toast.makeText(DetalheSonhoActivity.this, "ERRO",
							Toast.LENGTH_LONG).show();
					progress.dismiss();
				}
			} else {
				Toast.makeText(DetalheSonhoActivity.this, "ERRO",
						Toast.LENGTH_LONG).show();
				progress.dismiss();
			}

		}

	}

	private class ParticiparSonhoTask extends
			AsyncTask<SonhoBeanTO, Void, Boolean> {

		private ProgressDialog p;

		@Override
		protected void onPreExecute() {

			p = ProgressDialog.show(DetalheSonhoActivity.this, "Aguarde...",
					"Participando...");

		}

		@Override
		protected Boolean doInBackground(SonhoBeanTO... params) {

			SonhoService service = new SonhoService();
			Boolean result = service.participarSonho(params[0]);
			return result;

		}

		@Override
		protected void onPostExecute(Boolean result) {

			p.dismiss();
			Toast.makeText(DetalheSonhoActivity.this,
					"Solicitacao enviada, aguarde a resposta!",
					Toast.LENGTH_LONG).show();
			Intent intent = new Intent(DetalheSonhoActivity.this,
					ListaSonhosActivity.class);
			startActivity(intent);

		}
	}

}
